﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Reflection;

namespace Experts.Framework.Validate
{
    /// <summary>
    /// 把校验逻辑封装到特性里
    /// </summary>
    public static class ValidateExtend
    {
        public static bool Validate<T>(this T t)   //加个this把它变成扩展方法
        {
            Type type = t.GetType();
            foreach(var prop in type.GetProperties())
            {
                if(prop.IsDefined(typeof(AbstractValidateAttribute),true))
                {
                    object oValue = prop.GetValue(t);  //获取这个属性的值
                    foreach(AbstractValidateAttribute attribute in prop.GetCustomAttributes<AbstractValidateAttribute>())
                    {
                        if(!attribute.Validate(oValue))
                        {
                            return false;
                        }
                    }
                }
                //if(prop.IsDefined(typeof(RequiredAttribute),true))
                //{
                //    object oValue = prop.GetValue(t);  //获取这个属性的值 
                //    if(oValue==null || string.IsNullOrWhiteSpace(oValue.ToString()))
                //    {
                //        return false;
                //    }
                       
                //}
            }
            return true;
        }
    }
}
